import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'

import instance from '@/utils/request.js';
import { Toast } from 'vant';

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home,
    meta: { requiresAuth: false }
  },
  {
    path: '/about',
    name: 'About',
    component: () => import('../views/About.vue')
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('../views/Register.vue'),
    meta: { requiresAuth: false }
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/Login.vue'),
    meta: { requiresAuth: false }
  },
  {
    path: '/user',
    name: 'User',
    component: () => import('../views/user')
    // component: () => import('../views/user/index.vue')
  },
  {
    path: '/article',
    name: 'Article',
    component: () => import('../views/article'),
    meta: { requiresAuth: true }
  },
  {
    path: '/koubeilist',
    name: 'KoubeiList',
    component: () => import('../views/koubei/KoubeiList'),
    meta: { requiresAuth: false }
  },
  {
    path: '/koubeidetail',
    name: 'KoubeiDetail',
    component: () => import('../views/koubei/KoubeiDetail'),
    meta: { requiresAuth: false }
  },
  {
    path: '/koubeiadd',
    name: 'KoubeiAdd',
    component: () => import('../views/koubei/KoubeiAdd'),
    meta: { requiresAuth: false }
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})


// 路由守卫
// 路由实例对象router有一个beforeEach()方法，在进入路由之前做什么事
// 这个方法里面是一个回调函数，这个回调函数有三个参数：to, from ,next
// to 到哪里去；  from 从哪里来； next 通过

// 想要进入哪个路由，先经过路由守卫的同意
router.beforeEach(function (to, from, next) {
  if (to.meta.requiresAuth) {
    
    instance({
      method: 'post',
      url: '/user/verifyToken'
    }).then(r => {
      // console.log(r.data);
      if (r.data.code === 0) {
        // 通过
        next();
      } else {
        Toast.fail('本栏目需要登录才能访问')
        router.replace('/login')
      }

    })

  } else {
    next();
  }
})

export default router
